package com.example.studymvvmproject01.http

import android.util.Log
import com.example.studymvvmproject01.Api
import com.example.studymvvmproject01.http.intercept.AddCookiesInterceptor
import com.example.studymvvmproject01.http.intercept.ReceivedCookiesInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitClient{

    private const val CALL_TIMEOUT = 10L
    private const val CONNECT_TIMEOUT = 20L
    private const val IO_TIMEOUT = 20L
    private   val mRetrofit:Retrofit


    init {
        val loggingInterceptor = HttpLoggingInterceptor { Log.d("httpLog", it) }
        loggingInterceptor.level=HttpLoggingInterceptor.Level.BODY
        /**
         * OkHttpClient
         */
        val okHttpClient=OkHttpClient.Builder()
            .callTimeout(CALL_TIMEOUT, TimeUnit.SECONDS)
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(IO_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(IO_TIMEOUT, TimeUnit.SECONDS)
                //添加头部信息
            .addInterceptor(AddCookiesInterceptor())
                //拦截接口头部信息
//            .addInterceptor(ReceivedCookiesInterceptor())
                //日志拦截
            .addInterceptor(loggingInterceptor)
            .retryOnConnectionFailure(true)
            .build()
        mRetrofit= Retrofit.Builder().client(okHttpClient)
            .baseUrl(Api.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()


    }

    fun <T> create(tClass: Class<T>?): T {
        return mRetrofit.create(tClass)
    }
}